﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TencentYoutuYun.SDK.Csharp.Common;
using TencentYoutuYun.SDK.Csharp.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;

namespace TencentYoutuYun.SDK.Csharp
{
    public class FaceApi
    {

        // 设置为你自己的密钥对
        static string appid = "10008566";
        static string secretId = "AKIDW1SltqWBanpfLqgPiuvlT3YxFPSKN676";
        static string secretKey = "EORK2c4LUglgPxKxpsqdEdrvoV0KSQDp";
        static string userid = "464432262";

        /// <summary>
        /// 人脸检测
        /// 面部属性包括性别(gender), 年龄(age), 表情(expression), 魅力(beauty), 眼镜(glass)和姿态(pitch，roll，yaw).
        /// </summary>
        /// <param name="base64Str">图片base64</param>
        /// <returns></returns>
        public static DetectfaceViewModel api_detectface_base64(string base64Str)
        {
            //Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().TENCENTYUN_END_POINT);
            Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().YOUTU_END_POINT);

            double EXPIRED_SECONDS = 2592000;
            string expired = Utility.UnixTime(EXPIRED_SECONDS);
            string methodName = "youtu/api/detectface";
            StringBuilder postData = new StringBuilder();
            string pars = "\"app_id\":\"{0}\",\"image\":\"{1}\"";
            pars = string.Format(pars, Conf.Instance().APPID, base64Str);
            postData.Append("{");
            postData.Append(pars);
            postData.Append("}");

            string result = Http.HttpPost(methodName, postData.ToString(), Auth.appSign(expired, Conf.Instance().USER_ID));            
            DetectfaceViewModel temp = JsonConvert.DeserializeObject<DetectfaceViewModel>(result);
            return temp;
        }

        public static DetectfaceViewModel api_detectface_path(string imgPath)
        {
            Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().TENCENTYUN_END_POINT);

            double EXPIRED_SECONDS = 2592000;
            string expired = Utility.UnixTime(EXPIRED_SECONDS);
            string methodName = "youtu/api/detectface";
            StringBuilder postData = new StringBuilder();
            string pars = "\"app_id\":\"{0}\",\"image\":\"{1}\"";
            pars = string.Format(pars, Conf.Instance().APPID, Utility.ImgBase64(imgPath));
            postData.Append("{");
            postData.Append(pars);
            postData.Append("}");

            string result = Http.HttpPost(methodName, postData.ToString(), Auth.appSign(expired, Conf.Instance().USER_ID));
            DetectfaceViewModel temp = JsonConvert.DeserializeObject<DetectfaceViewModel>(result);
            return temp;
        }


        /// <summary>
        /// 计算两个Face的相似性以及五官相似度。
        /// </summary>
        /// <param name="base64StrA">base64图片</param>
        /// <param name="base64StrB">base64图片</param>
        /// <returns></returns>
        public static FacecompareViewModel api_facecompare(string base64StrA, string base64StrB)
        {
            Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().TENCENTYUN_END_POINT);

            double EXPIRED_SECONDS = 2592000;
            string expired = Utility.UnixTime(EXPIRED_SECONDS);
            string methodName = "youtu/api/facecompare";
            StringBuilder postData = new StringBuilder();
            string pars = "\"app_id\":\"{0}\",\"imageA\":\"{1}\",\"imageB\":\"{2}\"";
            pars = string.Format(pars, Conf.Instance().APPID, base64StrA, base64StrB);
            postData.Append("{");
            postData.Append(pars);
            postData.Append("}");
            string result = Http.HttpPost(methodName, postData.ToString(), Auth.appSign(expired, Conf.Instance().USER_ID));

            FacecompareViewModel temp = JsonConvert.DeserializeObject<FacecompareViewModel>(result);
            return temp;
        }


        /// <summary>
        /// 人脸五官定位        
        /// </summary>
        /// <param name="base64Str">图片base64</param>
        /// <returns></returns>
        public static ApiFaceshapeViewModel api_faceshape_base64(string base64Str)
        {
            Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().TENCENTYUN_END_POINT);

            double EXPIRED_SECONDS = 2592000;
            string expired = Utility.UnixTime(EXPIRED_SECONDS);
            string methodName = "youtu/api/faceshape";
            StringBuilder postData = new StringBuilder();
            string pars = "\"app_id\":\"{0}\",\"image\":\"{1}\"";
            pars = string.Format(pars, Conf.Instance().APPID, base64Str);
            postData.Append("{");
            postData.Append(pars);
            postData.Append("}");

            string result = Http.HttpPost(methodName, postData.ToString(), Auth.appSign(expired, Conf.Instance().USER_ID));
            ApiFaceshapeViewModel temp = JsonConvert.DeserializeObject<ApiFaceshapeViewModel>(result);
            return temp;
        }

        public static ApiFaceshapeViewModel api_faceshape_path(string imgPath)
        {
            Conf.Instance().setAppInfo(appid, secretId, secretKey, userid, Conf.Instance().TENCENTYUN_END_POINT);

            double EXPIRED_SECONDS = 2592000;
            string expired = Utility.UnixTime(EXPIRED_SECONDS);
            string methodName = "youtu/api/faceshape";
            StringBuilder postData = new StringBuilder();
            string pars = "\"app_id\":\"{0}\",\"image\":\"{1}\"";
            pars = string.Format(pars, Conf.Instance().APPID, Utility.ImgBase64(imgPath));
            postData.Append("{");
            postData.Append(pars);
            postData.Append("}");

            string result = Http.HttpPost(methodName, postData.ToString(), Auth.appSign(expired, Conf.Instance().USER_ID));
            ApiFaceshapeViewModel temp = JsonConvert.DeserializeObject<ApiFaceshapeViewModel>(result);
            return temp;
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="iSource">图片文件</param>
        /// <param name="outPath">路径</param> 例如 var outPath = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
        /// <param name="flag">值越大代表图片质量越好，一般默认控制在50为最佳压缩质量</param>
        /// <returns></returns>
        public static bool ReduceImage(Image iSource, string outPath, int flag)
        {
            ImageFormat tFormat = iSource.RawFormat;
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                    iSource.Save(outPath, jpegICIinfo, ep);
                else
                    iSource.Save(outPath, tFormat);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
            }
        }
    }
}
